package com.atguigu4.JDBCUtilsTest;

import com.beans.Customers;
import com.utils.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

/**
 * @auther user
 * @date 2021/12/10 - 6:04
 */
public class JDBCUtilsTest {
    @Test
    public void testGetCustomersById() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //1 获取连接
            //不使用数据库连接池技术
            //connection = JDBCUtils.getConnection();
            //使用C3P0数据库连接池技术
            //connection = JDBCUtils.getConnection1();
            //使用DBCP数据库连接池技术
            //connection = JDBCUtils.getConnection2();
            //使用druid德鲁伊数据库连接池技术
            connection = JDBCUtils.getConnection3();
            //2 预编译sql,返回PreparedSeatment实例
            String sql = "select id,name,email,birth from customers where id = ?";
            preparedStatement = connection.prepareStatement(sql);
            //3 填充占位符
            preparedStatement.setObject(1,26);
            //4 运行，返回ResultSet结果集
            resultSet = preparedStatement.executeQuery();
            //5 处理结果集
            //5.1 获取元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //5.2 获取总列数
            int columnCount = metaData.getColumnCount();
            if (resultSet.next()){
                Customers customers = new Customers();
                for (int i = 0; i < columnCount; i++) {
                    //获取列别名
                    String columnLabel = metaData.getColumnLabel(i+1);
                    //获取列值
                    Object columnValue = resultSet.getObject(i + 1);
                    //通过反射，将columnValue存储到customers对象的columnLabel属性中
                    Field field = Customers.class.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(customers,columnValue);
                }
                System.out.println(customers);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //6 关闭资源
            JDBCUtils.closeResource(connection,preparedStatement,resultSet);
        }
    }
}
